package edu.gatech.ece6102;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * User: deepal
 * Date: Nov 15, 2010
 * Time: 11:25:56 PM
 */
public class NetworkLogger implements Logger {

    Socket logger;
    OutputStream out;
    InputStream in = null;

    public NetworkLogger(String ip, int port) throws Exception{
        logger = new Socket(ip, port);
        out = logger.getOutputStream();
        in = logger.getInputStream();
    }

    public String store(byte[] message) {
        String str = "P0000";
        int length = message.length;
        String key = "";
        if (length < 100) {
            str = str + "00" + length;
        } else if (length < 1000) {
            str = str + "0" + length;
        } else {
            str = str + length;
        }
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            bout.write(str.getBytes());
            bout.write(message);
            out.write(bout.toByteArray());
            out.flush();
            byte[] buf = new byte[2048];
            int n;
            try {
                while ((n = in.read(buf)) < 0) {
                }
                key = new String(buf, 1, n);
            } catch (SocketException se) {
                if (se.getMessage().startsWith("Connection reset by peer")) {
                    System.out.println("Found error on Tomcat");
                }
            }
        } catch (IOException e) {
        }
        return key;
    }

    public byte[] retrieve(String id) {
        String get = "G" + id + "\n";
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            out.write(get.getBytes());
            out.flush();
            byte buf[] = new byte[4096];
            int n;
            while ((n = in.read(buf)) < 0) {
            }
            bout.write(buf, 0, n);
        } catch (IOException e) {

        }
        return bout.toByteArray();
    }

    public void delete(String id) {
        try {
            String get = "R" + id + "\n";
            out.write(get.getBytes());
            out.flush();
        } catch (IOException e) {
        }
    }
}
